package mo.leetcode_top;

import mo.common.ListNode;

import java.util.Arrays;

public class L19 {

    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head.next == null) {
            return null;
        }
        ListNode first = head;
        ListNode firstParent = new ListNode(-1);
        firstParent.next = head;
        ListNode second = head;
        while (n > 1) {
            second = second.next;
            n--;
        }
        while (second.next != null) {
            second = second.next;
            first = first.next;
            firstParent = firstParent.next;
        }
        if (firstParent.next == head) {
            firstParent.next = firstParent.next.next;
            return firstParent.next;
        } else {
            firstParent.next = firstParent.next.next;
            return head;
        }
    }

    public static void main(String[] args) {
        L19 test = new L19();
        ListNode head = ListNode.convertList2ListNode(Arrays.asList(1, 2, 3, 4, 5));
        ListNode res = test.removeNthFromEnd(head, 5);
        if (res != null) {
            res.print();
        }

    }

}
